<?php
include_once dirname(dirname(dirname(__FILE__))).'/include/db_connect.php';
function getDutyTable() {
	$conn = get_db_conn();
	$sql = 'select * from duty_table limit 0,1;';
	$result = mysql_query($sql,$conn) or die("db error");
	$row = mysql_fetch_array($result);
	$ret = json_decode($row['table_content'],true);
	return $ret;
}
function getDutyTableUpdateTime() {
	$conn = get_db_conn();
	$sql = 'select update_time from duty_table limit 0,1;';
	$result = mysql_query($sql,$conn) or die("db error");
	$row = mysql_fetch_array($result);
	return $row['update_time'];
}
function getDutyTableId() {
	$conn = get_db_conn();
	$sql = 'select id from duty_table limit 0,1;';
	$result = mysql_query($sql,$conn) or die("db error");
	$row = mysql_fetch_array($result);
	return $row['id'];
}
function getDutyUser() {
	$conn = get_db_conn();
	$sql = 'select id,user_real_name from user where is_user_on_duty = 1;';
	$result = mysql_query($sql,$conn) or die("db error");
	$ret = array();
	$cnt = 0;
	while($row = mysql_fetch_array($result)) {
		$ret[$row['id']]=$row['user_real_name'];
	}
	return $ret;
}

function print_option_list() {
	$conn = get_db_conn();
	$sql = 'select id,available_time from user where is_user_on_duty = 1;';
	$result = mysql_query($sql,$conn) or die("db error");
	$user_name = getDutyUser();
	$user_list = array();
	while($row = mysql_fetch_array($result)) {
		$user_list[$row['id']]=json_decode($row['available_time'],true);
	}
	$time['a']='7:30~10:00';$time['b']='10:00~12:30';
	$time['c']='12:30~14:30';$time['d']='14:30~16:00';
	$time['e']='16:00~18:30';$time['f']='18:30~22:30';
	foreach(range('a', 'f') as $item) {
		echo '<tr>';
		echo '<td style="vertical-align:middle;">'.$time[$item].'</td>';
		for($i=1;$i<=7;$i++) {
			echo '<td>';
			echo '<select class="form-control" id="'.$i.'_'.$item.'" name="'.$i.'_'.$item.'">';
			echo '<option value="0"></option>';
			foreach ($user_list as $id => $table) {
				if($table[$i][$item]=="1")echo '<option value="'.$id.'" style="color:#f00">'.$user_name[$id].'</option>';
				else echo '<option value="'.$id.'">'.$user_name[$id].'</option>';
			}
			echo '</select>';
			echo '</td>';
		}
		echo '</tr>';
	}
}
function updateTable($table) {
	$sql = "";
	$id = getDutyTableId();
	if($id!=null&&$id!='') {
		$sql.= 'update duty_table set table_content = \''.$table.'\',update_time = "'.date('Y-m-d H:i:s').'" where id = '.$id.';';
	}
	else {
		$sql.= 'insert into duty_table(table_content,update_time) values(\''.$table.'\',"'.date('Y-m-d H:i:s').'");';
	}
	$conn = get_db_conn();
	mysql_query($sql,$conn) or die("db error");
	return true;
}